window.addEventListener("DOMContentLoaded", async () => {
    const { ipcRenderer } = require("electron");

    const content = document.querySelector(".content");
    const allContent = document.querySelector(".allContent");
    const addHostCard = document.querySelector(".addHostCard");
    // const setting = document.querySelector(".setting");
    addHostCard.onclick = () => {
        let key = null;
        for (let k in hostData) {
            key = k;
        }
        hostData[++key] = {
            data: [{ ip: "127.0.0.1", web: "localhost", enable: true }],
            name: "local",
            enable: true,
            isSelect: false,
        };
        setHost();
        drawContent();
    };
    // setting.onclick = () => {
    //     console.log("setting");
    // };
    let hostData = await ipcRenderer.invoke("getHostData");
    let contentData = {};
    drawContent();
    async function setHost() {
        await ipcRenderer.invoke("setHost", JSON.stringify(hostData));
    }
    function initEvent() {
        groupItemSwitch();
        groupItemnameToSelect();
        editItemName();
        changeHostContent();
        changeOneHostUse();
    }
    function changeHostContent() {
        let areaGroup = document.querySelectorAll("textarea");
        for (let i = 0; i < areaGroup.length; i++) {
            let item = areaGroup[i];
            item.oninput = () => {
                let data = [];
                let key = item.getAttribute("data");

                if (item.value.indexOf("\n") >= 0) {
                    item.value.split("\n").map((item) => {
                        item = item.trim();
                        if (item.indexOf("#") >= 0) {
                            data.push({
                                content: item,
                                enable: false,
                            });
                        } else if (item.indexOf(" ") >= 0) {
                            data.push({
                                ip: item.split(" ")[0],
                                web: item.split(" ")[1],
                                enable: true,
                            });
                        } else {
                            data.push({
                                content: item ? "#" + item : "#",
                                enable: false,
                            });
                        }
                    });
                    hostData[key].data = data;
                    setHost();
                    resetNum(item.parentNode, key);
                    drawContent(false);
                }
            };
        }
    }
    function resetNum(parentNode, key) {
        let count = "";
        let index = 1;
        let itemIndex = 1;
        hostData[key].data.map((item) => {
            if (item.content) {
                count += `<div class="numItem"></div>`;
                itemIndex++;
            } else {
                count += `<div class="numItem ${item.enable ? "isUse" : ""}" data="${item.enable}-${key}-${itemIndex++}">${index++}</div>`;
            }
        });
        parentNode.querySelector(".count").innerHTML = count;
    }
    function changeOneHostUse() {
        let numItem = document.querySelectorAll(".numItem");
        for (let i = 0; i < numItem.length; i++) {
            let item = numItem[i];
            if (item.innerHTML) {
                item.onclick = () => {
                    let data = item.getAttribute("data").split("-");
                    let enable = data[0];
                    let key = data[1];
                    let i = parseInt(data[2]) - 1;
                    hostData[key].data[i].enable = !hostData[key].data[i].enable;
                    item.setAttribute("data", `${hostData[key].data[i].enable}-${key}-${i + 1}`);
                    if (hostData[key].data[i].enable) {
                        item.className = "numItem isUse";
                    } else {
                        item.className = "numItem";
                    }
                    setHost();
                    drawContent(false);
                };
            }
        }
    }
    function groupItemnameToSelect() {
        let contentCard = document.querySelectorAll(".contentCard");
        let content = document.querySelector(".content");
        for (let i = 0; i < contentCard.length; i++) {
            let item = contentCard[i];
            let key = item.getAttribute("data");
            item.onmousedown = (e) => {
                for (let k in hostData) {
                    hostData[k].isSelect = false;
                    if (key == k) {
                        hostData[k].isSelect = true;
                    }
                }
                for (let i = 0; i < content.childNodes.length; i++) {
                    let domItem = content.childNodes[i];
                    domItem.className = "contentCard";
                    if (domItem.getAttribute("data") == key) {
                        domItem.className = "contentCard isSelect";
                    }
                }
                switch (e.button) {
                    case 2:
                        let deleteGroup = document.querySelector(".deleteGroup");
                        deleteGroup.innerHTML = "";
                        let div = document.createElement("div");
                        div.className = "deleteItem";
                        div.innerHTML = "删除";
                        div.style.cssText = `top:${e.y}px;left:${e.x}px;`;
                        deleteGroup.appendChild(div);
                        div.onclick = (e) => {
                            e.stopPropagation();
                            removeOneHost();
                            deleteGroup.innerHTML = "";
                        };
                        return;
                    default:
                        return;
                }
            };
        }
    }
    function editItemName() {
        let groupItemname = document.querySelectorAll(".groupItemname");
        for (let i = 0; i < groupItemname.length; i++) {
            let item = groupItemname[i];
            let key = item.getAttribute("data");
            item.ondblclick = () => {
                item.childNodes[0].className = "nameHide";
                item.childNodes[1].className = "nameShow";
                item.childNodes[1].onblur = () => {
                    hostData[key].name = item.childNodes[1].value;
                    item.childNodes[0].innerHTML = item.childNodes[1].value;
                    item.childNodes[1].className = "nameHide";
                    item.childNodes[0].className = "nameShow";
                    setHost();
                };
            };
        }
    }
    function groupItemSwitch() {
        let groupItemSwitch = document.querySelectorAll(".groupItemSwitch");
        for (let i = 0; i < groupItemSwitch.length; i++) {
            let item = groupItemSwitch[i];
            item.onclick = () => {
                hostData[item.getAttribute("data")].enable = !hostData[item.getAttribute("data")].enable;
                if (hostData[item.getAttribute("data")].enable) {
                    item.className = "groupItemSwitch active";
                } else {
                    item.className = "groupItemSwitch";
                }
                setHost();
                drawContent();
            };
        }
    }
    function drawContent(isContent = true, isAllContent = true) {
        console.log(hostData);
        if (isContent) content.innerHTML = "";
        if (isAllContent) allContent.innerHTML = "";
        for (let key in hostData) {
            let data = "";
            let count = "";
            let index = 1;
            let itemIndex = 1;
            hostData[key].data.map((item) => {
                if (isContent) {
                    if (item.content) {
                        data += `${item.content}\n`;
                        count += `<div class="numItem"></div>`;
                        itemIndex++;
                    } else {
                        data += `${item.ip} ${item.web}\n`;
                        count += `<div class="numItem ${item.enable ? "isUse" : ""}" data="${item.enable}-${key}-${itemIndex++}">${index++}</div>`;
                    }
                }
                if (hostData[key].enable && item.enable) {
                    if (isAllContent) {
                        allContent.innerHTML += `<div class="allContentItem"><div class="ip">${item.ip}</div><div class="web">${item.web}</div></div>`;
                    }
                }
            });
            if (isContent) {
                content.innerHTML += `<div class="contentCard ${
                    hostData[key].isSelect ? "isSelect" : ""
                }" data="${key}"><div class="groupItem"><div class="groupItemname" data="${key}"><div class="nameShow">${hostData[key].name}</div><input class="nameHide" type="text" value="${
                    hostData[key].name
                }" /></div><div class="groupItemSwitch ${
                    hostData[key].enable ? "active" : ""
                }" data="${key}"></div></div><div class="contentData"><div class="count">${count}</div><textarea data="${key}">${data}</textarea></div></div>`;
                contentData[key] = count + data;
            }
        }
        initEvent();
    }
    function removeOneHost() {
        for (let k in hostData) {
            if (hostData[k].isSelect) {
                delete hostData[k];
                break;
            }
        }
        setHost();
        drawContent();
    }
    allContent.onmousedown = () => {
        let deleteGroup = document.querySelector(".deleteGroup");
        deleteGroup.innerHTML = "";
    };
});
